<template>
    <div class="main coupon-list">
        <section>
            <div v-if="rightsButtons['add']" class="btn-block"> 
              <el-button type="success" size="small" icon="el-icon-circle-plus" plain @click="showAdd">新建活动</el-button>
            </div>
            <el-form ref="searchForm" class="search-block" :model="listQuery" label-position="right" label-width="96px">
                <el-row :gutter="50">
                    <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                        <el-form-item label="活动名称：" prop="title">
                            <el-input @keyup.enter.native="search" v-model="listQuery.title" placeholder="活动名称" maxlength="50" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                        <el-form-item label="活动时间：" prop="tempDateRange">
                            <el-date-picker
                                    v-model="tempDateRange"
                                    type="daterange"
                                    range-separator="~"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
                        <el-form-item label="活动状态：" prop="activityState">
                            <el-select v-model="listQuery.status" clearable placeholder="请选择">
                                <el-option v-for="(value, key) in activityStateData" :key="key" :label="value" :value="key"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="" class="btn-item">
                    <el-button type="primary" size="mini" icon="el-icon-search" plain @click="search">搜索</el-button>
                    <span class="btn-reset" @click="resetForm('searchForm')">清空搜索条件</span>
                </el-form-item>
            </el-form>
            <el-table :data="list" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
                <el-table-column align="center" label="活动id" prop="id"></el-table-column>
                <el-table-column align="center" label="活动名称" prop="title">
                  <template slot-scope="scope">                      
                        <a style="color: #409eff" target="_blank" :href="getActivityUrlTwo({id: scope.row.id, isHide:scope.row.showTitle})">
                            {{scope.row.title}}
                        </a>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="活动时间" width="350px">
                  <template slot-scope="scope">
                    <span>{{scope.row.startTime}}</span><span>至</span><span>{{scope.row.endTime}}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="活动状态">
                    <template slot-scope="scope">
                       <span v-show="scope.row.status===1">未开始</span>
                       <span v-show="scope.row.status===2">活动中</span>
                       <span v-show="scope.row.status===3">已结束</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="是否启用" prop="enable">
                    <template slot-scope="scope">
                       <span>{{scope.row.enable===true?'是':'否'}}</span>  
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                      <el-button v-if="rightsButtons['edit']" type="text" @click="showEdit(scope.row)">编辑</el-button>
                      <el-button v-if="rightsButtons['goods']" type="text" @click="goodsEdit(scope.row)">商品管理</el-button>
                   </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="listQuery.pageNo"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="listQuery.pageSize"
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="listTotal">
            </el-pagination>
        </section>
        <el-dialog :title="promotionDTO.id ? '编辑活动' : '新建活动'" :visible.sync="dialogFormVisible">
            <el-form :model="promotionDTO"  size="medium" ref="form" label-width="150px">
            <div class="block-content">
                <el-form-item label="活动名称:" prop="title" :rules="commonRules.notNullRule">
                    <el-input v-model="promotionDTO.title" placeholder="请输入活动名称" ></el-input>
                </el-form-item>            
                <el-form-item label="活动开始时间:" prop="startTime" :rules="commonRules.notNullRule">
                  <el-date-picker
                    v-model="promotionDTO.startTime"
                    type="datetime"
                    placeholder="开始时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss"
                    >
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="活动结束时间:" prop="endTime" :rules="commonRules.notNullRule">
                  <el-date-picker
                    v-model="promotionDTO.endTime"
                    type="datetime"
                    placeholder="结束日期"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss"
                
                >
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="活动类型" prop="type" :rules="commonRules.notNullRule">
                  <el-select v-model="promotionDTO.type">
                    <el-option v-for="(name, val) in typeList" :key="val" :label="name.name" :value="name.id"></el-option>
                  </el-select>   
                </el-form-item>
                <el-form-item label="是否启用:" prop="enable">
                    <el-switch
                            v-model="promotionDTO.enable"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            :active-value="true"
                            :inactive-value="false"
                            >
                    </el-switch>
                </el-form-item>
            </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" :loading="btnLoading" :disabled="btnLoading">保存</el-button>
                <el-button @click="dialogFormVisible = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    export default {
      name: 'activityActivity',
      data(){
        return {
          activityStateData: {
            '1': '未开始',
            '2': '活动中',
            '3': '已结束'
          },
          listLoading: false,
          listQuery: {
            title: '',
            startTime: '',
            endTime: '',
            status: '',
            pageNo: 1,
            pageSize: 10,
            type:1 
          },
          tempDateRange:'',
          list: [],
          listTotal: 0,
          btnLoading:false,
          dialogFormVisible:false,
          promotionDTO:{
            title:'',
            startTime:'',
            endTime:'',
            enable:false,
            id:'',
            type: 1,
            template:''
          },
          typeList:[
            {id:1, name:'N件N元'}
          ]
        }
      },
      created(){
        this.getList();
      },
      beforeRouteEnter(to, from, next){
        next(vm => {
            if(from.name==='activityListEdit'){
                vm.listQuery = JSON.parse(localStorage.getItem('activityListQuery'))   
                vm.getList()
            }
        })
        next()
      },
      methods: {
        goodsEdit(aaa){
          localStorage.setItem('activityListQuery', JSON.stringify(this.listQuery))
          sessionStorage.setItem('newH5ActivityDetail', JSON.stringify(aaa))
          this.$router.push({ name: 'activityActivityGoods', query: { id: aaa.id } })
        },
        
        // 获取列表
        getList () {
          this.listLoading = true;
          let date = this.tempDateRange;
          console.log(date)
          this.listQuery.startTime = date && date.length ? date[0] + ' 00:00:00': '';
          this.listQuery.endTime = date && date.length ? date[1] + ' 23:59:59' : '';
          this.request({
            url: '/promotion',
            method: 'get',
            params: this.listQuery
          }).then(({data}) => {
            this.list = data.records;
            this.listTotal = data.total;
            this.listLoading = false;
          }).catch(err => {
            console.log(err);
            this.list = [];
            this.listTotal = 0;
            this.listLoading = false;
          });
        },
        // 清空搜索条件
        resetForm (formName) {
          this.$nextTick(() => {
            this.tempDateRange=''
            this.listQuery.status=''
            this.$refs[formName].resetFields()
            this.listQuery.pageNo = 1
            this.getList()
          })
        },
        // 搜索
        search() {
          this.listQuery.pageNo = 1;
          this.getList();
        },
        //切换每页条数
        handleSizeChange (value) {
          this.listQuery.pageSize = value;
          this.getList()
        },
        // 切换分页
        handleCurrentChange(page) {
          this.listQuery.pageNo = page;
          this.getList();
        },
        showEdit(row) {
          this.promotionDTO = Object.assign({}, row);
          this.dialogFormVisible = true;
          this.btnLoading = false;
          this.$nextTick(()=>{
              this.$refs.form.clearValidate()
          });
        },
        showAdd(){
            this.promotionDTO={
              title:'',
              startTime:'',
              endTime:'',
              enable:false,
              id:'',
              type: 1,
              template:''
            }
            this.dialogFormVisible = true;
            this.btnLoading = false;
            this.$nextTick(()=>{
                this.$refs.form.clearValidate()
            })
        },
        save() {
           this.$refs.form.validate(valid => {
              if (!valid) {
                return false;
              } 
              this.btnLoading = true;
              if(this.promotionDTO.id===''){
                  this.request({
                    url: '/promotion',
                    method: 'post',
                    data: this.promotionDTO
                  })
                  .then((res) => {
                    if(res.code===200){
                      this.btnLoading=false
                      this.dialogFormVisible = false;
                      this.getList()
                      this.$message({
                          message: '新建成功',
                          type: 'success'
                      })
                    }else {
                      this.$message({
                            message: '新建失败',
                            type: 'error'
                        })
                    }
                  }).catch(err => {
                    console.log(err)
                  })
              }else {
                this.request({
                    url: '/promotion/'+this.promotionDTO.id,
                    method: 'put',
                    data: this.promotionDTO
                  })
                  .then((res) => {
                    if(res.code===200){
                      this.btnLoading=false
                      this.dialogFormVisible = false
                      this.getList()
                      this.$message({
                            message: '编辑成功',
                            type: 'success'
                        })
                    }else {
                      this.$message({
                            message: '编辑失败',
                            type: 'error'
                        })
                    } 
                  }).catch(err => {
                    console.log(err);
                  })
              }
            })
          },
          dateFormat: (value, format) => {
            if (!value) return
            if (!(value instanceof Date)) {
                value = new Date(value)
            }
            let o = {
            'M+': value.getMonth() + 1, // month
            'd+': value.getDate(), // day
            'h+': value.getHours(), // hour
            'm+': value.getMinutes(), // minute
            's+': value.getSeconds(), // second
            'q+': Math.floor((value.getMonth() + 3) / 3), // quarter
            'S': value.getMilliseconds() // millisecond
            }

            if (!format || format === '') {
            format = 'yyyy-MM-dd hh:mm:ss'
            }

            if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (value.getFullYear() + '').substr(4 - RegExp.$1.length))
            }

            for (let k in o) {
            if (new RegExp('(' + k + ')').test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
            }
            }
            return format
        }       
      }
    }
</script>
<style lang="scss">
    @import "../../../styles/mixin";
    .use-range-block{
        @include flex;
        text-align: left;

        div{
            @include sub-item;
        }
    }
</style>
